#include "cameravideobuffer.h"
#include <QCameraInfo>
CameraVideoBuffer::CameraVideoBuffer(QObject *parent) :
    QAbstractVideoSurface(parent)
{
    mRunning=false;
    mCamId=0;
    mpCamera=NULL;
}
void CameraVideoBuffer::Push(QVideoFrame frame){
    mLock.lock();
    frame.map(QAbstractVideoBuffer::ReadOnly);
    mFrameBuffer.push_back(frame);
    mLock.unlock();
}
bool CameraVideoBuffer::top(QVideoFrame& first)
{
    mLock.lock();
    if(mFrameBuffer.isEmpty())
    {
        mLock.unlock();
        return false;
    }
    first = mFrameBuffer.front();
    mLock.unlock();
    return true;
}
void CameraVideoBuffer::Pop()
{
    mLock.lock();
    while(mFrameBuffer.size()>2)
    {
        mFrameBuffer.front().unmap();
        mFrameBuffer.pop_front();
    }
    mLock.unlock();
}

void CameraVideoBuffer::StartCamera()
{
    if(mpCamera==NULL)
    {
        QList<QCameraInfo> cameras = QCameraInfo::availableCameras();
        foreach (const QCameraInfo &cameraInfo, cameras) {
            qDebug()<<"cameraName:"<<cameraInfo.deviceName();
        }
        if(cameras.size()==0)
        {
            qDebug()<<"No Camera";
        }
        qDebug()<<"FaceVideoItem Camera Opened";
        qDebug()<<"select device:"<<mCamId;
        if(mCamId>=cameras.size())
            mCamId=0;
        mpCamera = new QCamera(cameras[mCamId]);
        mpCamera->setViewfinder(this);
        mpCamera->start();        
    }
}

void CameraVideoBuffer::StopCamera()
{
    if(mpCamera)
    {
        mpCamera->stop();
        delete mpCamera;
        mpCamera=NULL;
    }
}
